package com.example.gateway.app.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import com.example.gateway.app.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
@Order(value = -1)
@Slf4j
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono< Void > filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求路径
        String path = request.getURI().getPath();
        log.info("获取到请求路径：{}", path);
        // 2、判断是否是登录
        if (path.contains("/login")) {
            // 登录请求放行
            return chain.filter(exchange);
        }
        // 3、获取token
        String token = request.getHeaders().getFirst("token");
        // 4、判断token是否存在
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5、判断token是否有效
        Claims claimsBody = JwtUtil.getClaimsBody(token);
        int flag = JwtUtil.verifyToken(claimsBody);
        if (flag == 1 || flag == 2) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 获取用户id
        Object userId = claimsBody.get("id");
        // 添加userId到header
        ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.add("userId", userId + "");
        }).build();
        // 重置RequestServlet
        exchange.mutate().request(serverHttpRequest).build();
        // 6、将用户信息放入上下文中
        return chain.filter(exchange);
    }
}
